/**
 * 设置form内的表单元素内容
 * @param form
 * @param { name1: value1, name2: value2}
 * @example set_data(form:, data);
 */

export default function set_data(form: HTMLFormElement, data: {
	[name: string]: string | number | boolean | string[];
}) {
	for (const n in data) {
		const el = (() => {
			if (form[n]) {
				return form[n] as HTMLElement;
			} else {
				return form.querySelector<HTMLElement>('[name="' + n + '"]');
			}
		})();
		if (el) {
			const name = el.tagName;
			switch (name) {
				case 'INPUT':
					const input = el as HTMLInputElement;
					const t = input.type;
					switch (t) {
						case 'checkbox':
							{
								input.checked = data[n] === 'true' || data[n] === true ? true : false;
							}
							break;
						case 'radio':
							{
								input.checked = data[n] === 'true' || data[n] === true ? true : false;
							}
							break;
						case 'file':
							break;
						default:
							{
								input.value = data[n].toString();
							}
							break;
					}
					break;
				case 'TEXTAREA':
				case 'LABLE':
				case 'SPAN':
					const html = el as HTMLElement;
					html.innerHTML = data[n].toString();
					break;
				case 'SELECT':
					const select = el as HTMLSelectElement;
					(data[n] as string[]).forEach((item, i) => {
						select.options[i] = new Option(item, item);
					});
					break;
			}
		} else {
			console.warn('Could not find form control, name = ' + n);
		}
	}
}
